using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class ShippingCostControllerBase : BaseController
	{
		#region Members

        protected IShippingCostService _shippingCostService;

        #endregion

        #region Constructors

        public ShippingCostControllerBase(IShippingCostService shippingCostService)
        {
            _shippingCostService = shippingCostService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /ShippingCost
        // **************************************
		public virtual ActionResult Index()
		{
			IndexShippingCostViewModel viewModel = new IndexShippingCostViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<ShippingCost> searchList = _shippingCostService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _shippingCostService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from shippingCost in searchList     // Row data
                       select new
                       {
                           id = shippingCost.Id,                
                           cell = new string[] {
						   
                                shippingCost.RangeMin.ToString(),
								shippingCost.RangeMax.ToString(),
								shippingCost.Cost.ToString()
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _shippingCostService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<ShippingCost> _shippingCostList = _shippingCostService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("RangeMin;RangeMax;Cost");

            // rows
            foreach (ShippingCost shippingCost in _shippingCostList)
            {
                List<string> rowData = new List<string>() { shippingCost.RangeMin.ToString(), shippingCost.RangeMax.ToString(), shippingCost.Cost.ToString() };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "ShippingCost.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /ShippingCost/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            ShippingCost shippingCost = new ShippingCost();
            CreateShippingCostViewModel viewModel = Mapper.Map<ShippingCost, CreateShippingCostViewModel>(shippingCost);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateShippingCostViewModel shippingCostModel)
        {
            if (ModelState.IsValid)
            {
                ShippingCost shippingCost = new ShippingCost();
                AutoMapper.Mapper.Map<CreateShippingCostViewModel, ShippingCost>(shippingCostModel, shippingCost);
 

				_shippingCostService.Add(shippingCost);

                return RedirectToAction("Edit", new { id = shippingCost.Id});
            }
            else
            {

                return View(shippingCostModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /ShippingCost/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            ShippingCost shippingCost = _shippingCostService.Find(id);
            EditShippingCostViewModel viewModel = Mapper.Map<ShippingCost, EditShippingCostViewModel>(shippingCost);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditShippingCostViewModel shippingCostModel)
        {
            if (ModelState.IsValid)
            {
                ShippingCost shippingCost = _shippingCostService.Find(shippingCostModel.Id);
                AutoMapper.Mapper.Map<EditShippingCostViewModel, ShippingCost>(shippingCostModel, shippingCost);
                
				_shippingCostService.Change(shippingCost);

                return RedirectToAction("Index");
            }
            else
            {

                return View(shippingCostModel);
            }
		}
		

		#endregion

		#region Details

		// *******************************************
        // URL: /ShippingCost/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            ShippingCost shippingCost = _shippingCostService.Find(id);
            DetailsShippingCostViewModel viewModel = Mapper.Map<ShippingCost, DetailsShippingCostViewModel>(shippingCost);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
